package com.hg.library.utils;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.BatteryManager;
import android.os.storage.StorageEventListener;
import android.os.storage.StorageManager;
import android.provider.Settings;
import android.text.format.DateFormat;

import com.hg.library.Interface.SystemDevStateListener;
import com.hg.library.Interface.SystemStateInfoListener;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Calendar;
import java.util.Map;

/**
 * Created by ASUS-PC on 2016/5/9.
 */
public class SystemDevState extends StorageEventListener {

    private static SystemDevState systemDevState;

    private Context context;

    private boolean isStop;

    private UsbManager usbManager;

    private static SystemDevStateListener listener;


    private static SystemStateInfoListener systemStateInfoListener;

    public static final String TCARD_PATH = "/mnt/external_sd";

    int GLASSES_VENDOR_ID = 0x0416, GLASSES_PRODUCT_ID = 0x50A1;
    //1 为存在 ，0 为不存在
    int GLASSES_DEVICE_FLAG = 0;

    private static final String[] USB_PATHS = new String[]{"/mnt/usb_storage_sda/", "/mnt/usb_storage_sdb/", "/mnt/usb_storage_sdc/", "/mnt/usb_storage_sdd/", "/mnt/usb_storage_sde/"
            , "/mnt/usb_storage_sdf/", "/mnt/usb_storage_sdg/", "/mnt/usb_storage_sdh/", "/mnt/usb_storage_sdi/", "/mnt/usb_storage_sdj/", "/mnt/usb_storage_sdk/"
            , "/mnt/usb_storage_sdl/", "/mnt/usb_storage_sdm/", "/mnt/usb_storage_sdn/", "/mnt/usb_storage_sdo/", "/mnt/usb_storage_sdp/"};

    public static SystemDevState getInstance(Context context) {
        if (systemDevState == null) return systemDevState = new SystemDevState(context);
        return systemDevState;
    }

    private SystemDevState(final Context context) {
        this.context = context;
        usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
        registerReceiver();
    }

    private void registerReceiver() {
        registerBetteryReceiver();
        registerBluetoothReceiver();
        registerUsbDevReceiver();
        registerWifiReceiver();
        registerStorgeReceiver();
        registerTimeReceiver();
        StorageManager.from(context).registerListener(this);
        registerAirplaneReceiver();
    }

    private void registerAirplaneReceiver(){
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
        context.registerReceiver(airplaneReceiver, intentFilter);
    }

    private BroadcastReceiver airplaneReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (listener != null) listener.onAirplaneMode(intent.getBooleanExtra("state",false));
        }
    };

    private void registerTimeReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
        intentFilter.addAction(Intent.ACTION_TIME_CHANGED);
        intentFilter.addAction(Intent.ACTION_TIME_TICK);
        context.registerReceiver(timeChangeRecvive, intentFilter);
    }

    private BroadcastReceiver timeChangeRecvive = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
                requestTime();
            } else if (intent.getAction().equals(Intent.ACTION_TIMEZONE_CHANGED)) {
                requestTime();
            } else if (intent.getAction().equals(Intent.ACTION_TIME_CHANGED)) {
                requestTime();
            }
        }
    };

    private void requestTime() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        if (listener != null)
            listener.onTimeState((String) DateFormat.format("HH:mm", calendar));
    }

    private BluetoothAdapter bluetoothAdapter;

    private void registerBluetoothReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.bluetooth.a2dp.profile.action.CONNECTION_STATE_CHANGED");
        filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
        filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        filter.addAction("android.bluetooth.BluetoothAdapter.STATE_OFF");
        filter.addAction(Intent.ACTION_HEADSET_PLUG);
        context.registerReceiver(bluetoothReceiver, filter);
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    }

    private void registerUsbDevReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        context.registerReceiver(usbDevReceiver, filter);
    }

    private void registerBetteryReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
        intentFilter.addAction(Intent.ACTION_POWER_CONNECTED);
        intentFilter.addAction(Intent.ACTION_BATTERY_LOW);
        context.registerReceiver(mBatteryInfoReceiver, intentFilter);
    }

    private void registerStorgeReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_LOW);
        intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
        intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_FULL);
        context.registerReceiver(storegReceiver, intentFilter);
    }

    private BroadcastReceiver storegReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Intent.ACTION_DEVICE_STORAGE_LOW.equals(action)) {
                if (systemStateInfoListener != null) systemStateInfoListener.onStorageLow();
            } else if (Intent.ACTION_DEVICE_STORAGE_OK.equals(action)) {
                if (systemStateInfoListener != null) systemStateInfoListener.onStorageOk();
            } else if (Intent.ACTION_DEVICE_STORAGE_FULL.equals(action)) {
                if (systemStateInfoListener != null) systemStateInfoListener.onStorageFull();
            }
        }
    };


    private String chargingType = "unknown";
    private boolean bCharging = false;
    private boolean bFull = false;
    private int percent;
    private BroadcastReceiver mBatteryInfoReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
                //int percent=getBatteryLevel(intent);
                if (listener != null) getBatteryStatus(intent);
            } else if (Intent.ACTION_BATTERY_LOW.equals(action)) {
                if (systemStateInfoListener != null) systemStateInfoListener.onBatteryLow();
            }
        }
    };

    private void getBatteryStatus(Intent batteryChangedIntent) {
        final Intent intent = batteryChangedIntent;

        int level = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
        int scale = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
        percent = (level * 100) / scale;
        //Toast.makeText(context,"battery="+percent,Toast.LENGTH_SHORT).show();
        int plugType = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
        int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS,
                BatteryManager.BATTERY_STATUS_UNKNOWN);
        String statusString;
        if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
            chargingType = "unknown";
            if (plugType == BatteryManager.BATTERY_PLUGGED_AC) {
                chargingType = "ac";
            } else if (plugType == BatteryManager.BATTERY_PLUGGED_USB) {
                chargingType = "usb";
            } else if (plugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) {
                chargingType = "wireless";
            } else {
            }
            bCharging = true;
        } else {
            bCharging = false;
            if (status == BatteryManager.BATTERY_STATUS_DISCHARGING) {
                bFull = false;
            } else if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING) {
                bFull = false;
            } else if (status == BatteryManager.BATTERY_STATUS_FULL) {
                bCharging = false;
                bFull = true;
            } else {
                bFull = false;
            }
        }
        updateLevelCharging(percent);

    }

    private void updateLevelCharging(int per) {
        listener.onBatteryFullState(bFull);
        listener.onBatteryPercent(per);
        listener.onBatteryChargingState(bCharging);
    }

    private void getBatteryInfo() {

        try {
            BufferedReader reader = new BufferedReader(new FileReader(new File("/sys/class/power_supply/battery/status")));
            String p = reader.readLine();

            if (p != null && p.equals("Charging")){
                bCharging = true;
            }
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (percent == 0) {
            try {
                BufferedReader reader = new BufferedReader(new FileReader(new File("/sys/class/power_supply/battery/capacity")));
                String p = reader.readLine();
                updateLevelCharging(Integer.valueOf(p));
                reader.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            updateLevelCharging(percent);
        }

    }

    /**
     * 判断T卡是否插入
     */
    private void getSDCardInfo() {
        File root = new File(TCARD_PATH);
        File[] files = root.listFiles();
        if (files != null) {
            if (listener != null) listener.onSDCardState(true);
//            if (systemStateInfoListener != null) systemStateInfoListener.onSDCardState(true);
            return;
        } else {
            /*if (listener != null) listener.onSDCardState(false);
            if (systemStateInfoListener != null) systemStateInfoListener.onSDCardState(false);*/
        }
    }

    /**
     * 判断USB存储或设备是否插入
     */
    private void getUsbInfo() {

        if (isUsbDevicesExist()) {
            if (listener != null) listener.onUsbStorageState(true);
        } else {
            if (listener != null) listener.onUsbStorageState(false);
        }
    }

    private void getBluetoothInfo() {

        boolean enabled = bluetoothAdapter.isEnabled();

        if (enabled) {
            if (listener != null) listener.onBluetoothState(true);
        }else {
            if (listener != null) listener.onBluetoothState(false);
        }

        //可操控蓝牙设备，如带播放暂停功能的蓝牙耳机
        //int a2dp = bluetoothAdapter.getProfileConnectionState(BluetoothProfile.A2DP);
        //蓝牙头戴式耳机，支持语音输入输出
        //int headset = bluetoothAdapter.getProfileConnectionState(BluetoothProfile.HEADSET);
        //蓝牙穿戴式设备
        //int health = bluetoothAdapter.getProfileConnectionState(BluetoothProfile.HEALTH);

        /*if (a2dp == BluetoothProfile.STATE_CONNECTED || headset == BluetoothProfile.STATE_CONNECTED || health == BluetoothProfile.STATE_CONNECTED) {
            if (listener != null) listener.onBluetoothState(true);
            if (systemStateInfoListener != null) systemStateInfoListener.onBluetoothState(true);
        } else {
            *//*if (listener != null) listener.onBluetoothState(false);
            if (systemStateInfoListener != null) systemStateInfoListener.onBluetoothState(false);*//*
        }*/
    }

    private int getWifiInfo() {
        WifiManager wifiManager = (WifiManager) context.getSystemService(context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        if (wifiInfo.getBSSID() != null) {
            //wifi名称
            String ssid = wifiInfo.getSSID();
            //wifi信号强度
            int signalLevel = WifiManager.calculateSignalLevel(wifiInfo.getRssi(), 10);
            //wifi速度
            int speed = wifiInfo.getLinkSpeed();
            //wifi速度单位
            String units = WifiInfo.LINK_SPEED_UNITS;

            if (listener != null && wifiEnabled) listener.onWifiEnable();
            else if (listener != null && !wifiEnabled) listener.onWifiDisable();

            if (systemStateInfoListener != null && wifiEnabled)
                systemStateInfoListener.onWifiEnable();
            else if (systemStateInfoListener != null && !wifiEnabled)
                systemStateInfoListener.onWifiDisable();

            if (listener != null) listener.onWifiLevel(signalLevel);
            if (systemStateInfoListener != null) systemStateInfoListener.onWifiLevel(signalLevel);

            return signalLevel;
        }else {
            if (listener != null) listener.onWifiDisable();
        }
        return 0;
    }

    private void getAirplaneMode(){
        if (listener != null){
            boolean airplaneModeOn = Settings.Global.getInt(context.getContentResolver(),
                    Settings.Global.AIRPLANE_MODE_ON,
                    0) == 1;
            listener.onAirplaneMode(airplaneModeOn);
        }
    }

    private boolean isUsbDevicesExist() {

        int size = usbManager.getDeviceList().size();

        if (checkGlassesUsbDeviceIsExist()) {
            if (size > 1) return true;
        } else {
            if (size > 0) return true;
        }
        return false;
    }

    //检查眼镜设备是否存在，因为眼镜内置usb设备
    private boolean checkGlassesUsbDeviceIsExist() {
        for (Map.Entry<String, UsbDevice> entry : usbManager.getDeviceList().entrySet()) {

            int vendorId = entry.getValue().getVendorId();
            int productId = entry.getValue().getProductId();
            
            if (vendorId == GLASSES_VENDOR_ID && productId == GLASSES_PRODUCT_ID) {
                GLASSES_DEVICE_FLAG = 1;
                return true;
            }
        }
        GLASSES_DEVICE_FLAG = 0;
        return false;
    }

    private void registerWifiReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.RSSI_CHANGED_ACTION);
        context.registerReceiver(wifiBeceiver, filter);
    }

    private boolean wifiEnabled;

    private BroadcastReceiver wifiBeceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            if (intent.getAction().equals(WifiManager.RSSI_CHANGED_ACTION)) {
                if (listener != null) listener.onWifiLevel(getWifiInfo());
            } else if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
                NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
                if (info.getState().equals(NetworkInfo.State.DISCONNECTED)) {//如果断开连接
                    if (listener != null) listener.onWifiLevel(0);
                }
            } else if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
                //WIFI开关
                int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_DISABLED);
                if (wifiState == WifiManager.WIFI_STATE_DISABLED) {//如果关闭
                    if (listener != null) listener.onWifiDisable();
                    if (systemStateInfoListener != null) systemStateInfoListener.onWifiDisable();
                    wifiEnabled = false;
                } else if (wifiState == WifiManager.WIFI_STATE_ENABLED) {
                    if (listener != null) {
                        listener.onWifiEnable();
                        listener.onWifiLevel(0);
                    }
                    if (systemStateInfoListener != null) systemStateInfoListener.onWifiEnable();
                    wifiEnabled = true;
                }
            }
        }
    };

    private BroadcastReceiver usbDevReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            int GLASSES_FLAG_TEMP = GLASSES_DEVICE_FLAG;
            checkGlassesUsbDeviceIsExist();

            if (GLASSES_FLAG_TEMP != GLASSES_DEVICE_FLAG) return;//眼镜设备已插入或者拔出 不提示系统消息

            if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {

                if (systemStateInfoListener != null)
                    systemStateInfoListener.onUsbHandleState(true);//系统提示
                if (listener != null) listener.onUsbStorageState(true);

            } else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {

                if (listener != null && !isUsbDevicesExist()) listener.onUsbStorageState(false);
                if (systemStateInfoListener != null && !isUsbDevicesExist())
                    systemStateInfoListener.onUsbStorageState(false);
            }
        }
    };

    @Override
    public void onStorageStateChanged(String path, String oldState, String newState) {

        if (newState.equals("mounted") && systemStateInfoListener != null) {
            systemStateInfoListener.onUsbStorageState(true);//弹出activity
        } else if (newState.equals("removed")) {
            //usb存储设备移除
        }
    }

    private BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            //设备信息
            //BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

            if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {

                int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);

                if (state == BluetoothAdapter.STATE_ON) {
                    if (listener != null) listener.onBluetoothState(true);
                } else if (state == BluetoothAdapter.STATE_OFF) {
                    if (listener != null) listener.onBluetoothState(false);
                }

            } else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                //设备已发现！！
            } else if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
                //设备已连接！！
//                if (listener != null) listener.onBluetoothState(true);
                if (systemStateInfoListener != null) systemStateInfoListener.onBluetoothState(true);
            } else if (BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED.equals(action)) {
                //正在断开蓝牙连接。。。
            } else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
                //蓝牙连接已断开！！
//                if (listener != null) listener.onBluetoothState(false);
                if (systemStateInfoListener != null)
                    systemStateInfoListener.onBluetoothState(false);
            } else if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {//耳机
                if (intent.hasExtra("state")) {
                    if (intent.getIntExtra("state", 0) == 0) {
                        if (listener != null) listener.onHeadDevState(false);
                        if (systemStateInfoListener != null)
                            systemStateInfoListener.onHeadDevState(false);
                    } else {
                        if (listener != null) listener.onHeadDevState(true);
                        if (systemStateInfoListener != null)
                            systemStateInfoListener.onHeadDevState(true);
                    }
                }
            }
        }
    };
    private static final String TAG = "SystemDevState";

    public void registerSystemDevStateListener(SystemDevStateListener systemDevStateListener) {
        listener = systemDevStateListener;
        getInfo();
        getBatteryInfo();
        getAirplaneMode();
    }

    public void registerSystemStateInfoListener(SystemStateInfoListener systemStateInfoListener) {
        this.systemStateInfoListener = systemStateInfoListener;
        getInfo();
    }

    private void getInfo() {
        getBluetoothInfo();
        getSDCardInfo();
        getUsbInfo();
        getWifiInfo();
        requestTime();
    }

    public void unregisterSystemStateListener() {

        if (!isStop) {
            isStop = true;
            listener = null;
            systemDevState = null;
            context.unregisterReceiver(bluetoothReceiver);
            context.unregisterReceiver(wifiBeceiver);
            context.unregisterReceiver(mBatteryInfoReceiver);
            context.unregisterReceiver(usbDevReceiver);
            context.unregisterReceiver(storegReceiver);
            context.unregisterReceiver(timeChangeRecvive);
            context.unregisterReceiver(airplaneReceiver);
        }
    }

    public static boolean isUsbStorageInput(){
        for (int i = 0; i < USB_PATHS.length; i++) {
            File file = new File(USB_PATHS[i]);
            if (file.listFiles().length != 0){
                return true;
            }
        }
        return false;
    }
}
